import { configService } from '../../services/config-service';

export class ConversionHistory {
  constructor() {
    this.history = [];
    this.filteredHistory = [];
    this.isLoading = true;
    this.errorMessage = '';
    this.searchTerm = '';
    this.filterFormat = '';
    this.sortBy = 'date';
    this.sortOrder = 'desc';
    
    this.init();
  }

  async init() {
    try {
      await configService.loadConfig();
      this.loadHistory();
      this.isLoading = false;
    } catch (error) {
      console.error('初始化失败:', error);
      this.errorMessage = '初始化失败，请刷新页面重试';
      this.isLoading = false;
    }
  }

  loadHistory() {
    // 从本地存储加载历史记录
    const savedHistory = localStorage.getItem('conversionHistory');
    if (savedHistory) {
      try {
        this.history = JSON.parse(savedHistory);
        this.applyFilters();
      } catch (error) {
        console.error('加载历史记录失败:', error);
        this.history = [];
      }
    }
  }

  saveHistory() {
    try {
      localStorage.setItem('conversionHistory', JSON.stringify(this.history));
    } catch (error) {
      console.error('保存历史记录失败:', error);
    }
  }

  addHistoryRecord(record) {
    const historyItem = {
      id: Date.now().toString(),
      timestamp: new Date().toISOString(),
      originalName: record.originalName,
      sourceFormat: record.sourceFormat,
      targetFormat: record.targetFormat,
      fileSize: record.fileSize,
      status: record.status,
      error: record.error || null,
      downloadUrl: record.downloadUrl || null,
      convertedName: record.convertedName || null
    };

    this.history.unshift(historyItem);
    
    // 限制历史记录数量（最多保存100条）
    if (this.history.length > 100) {
      this.history = this.history.slice(0, 100);
    }
    
    this.saveHistory();
    this.applyFilters();
  }

  deleteHistoryItem(id) {
    this.history = this.history.filter(item => item.id !== id);
    this.saveHistory();
    this.applyFilters();
  }

  clearAllHistory() {
    this.history = [];
    this.filteredHistory = [];
    this.saveHistory();
  }

  applyFilters() {
    let filtered = [...this.history];

    // 搜索过滤
    if (this.searchTerm) {
      const term = this.searchTerm.toLowerCase();
      filtered = filtered.filter(item => 
        item.originalName.toLowerCase().includes(term) ||
        item.convertedName?.toLowerCase().includes(term)
      );
    }

    // 格式过滤
    if (this.filterFormat) {
      filtered = filtered.filter(item => 
        item.sourceFormat === this.filterFormat || 
        item.targetFormat === this.filterFormat
      );
    }

    // 排序
    filtered.sort((a, b) => {
      let aValue, bValue;
      
      switch (this.sortBy) {
        case 'date':
          aValue = new Date(a.timestamp);
          bValue = new Date(b.timestamp);
          break;
        case 'name':
          aValue = a.originalName.toLowerCase();
          bValue = b.originalName.toLowerCase();
          break;
        case 'size':
          aValue = this.parseFileSize(a.fileSize);
          bValue = this.parseFileSize(b.fileSize);
          break;
        case 'format':
          aValue = `${a.sourceFormat}-${a.targetFormat}`;
          bValue = `${b.sourceFormat}-${b.targetFormat}`;
          break;
        default:
          return 0;
      }

      if (aValue < bValue) return this.sortOrder === 'asc' ? -1 : 1;
      if (aValue > bValue) return this.sortOrder === 'asc' ? 1 : -1;
      return 0;
    });

    this.filteredHistory = filtered;
  }

  parseFileSize(sizeStr) {
    if (!sizeStr) return 0;
    const units = { 'B': 1, 'KB': 1024, 'MB': 1024 * 1024, 'GB': 1024 * 1024 * 1024 };
    const match = sizeStr.match(/^([\d.]+)\s*([A-Z]+)$/i);
    if (match) {
      const value = parseFloat(match[1]);
      const unit = match[2].toUpperCase();
      return value * (units[unit] || 1);
    }
    return 0;
  }

  setSearchTerm(term) {
    this.searchTerm = term;
    this.applyFilters();
  }

  setFilterFormat(format) {
    this.filterFormat = format;
    this.applyFilters();
  }

  clearFilters() {
    this.searchTerm = '';
    this.filterFormat = '';
    this.applyFilters();
  }

  setSortBy(sortBy) {
    if (this.sortBy === sortBy) {
      this.sortOrder = this.sortOrder === 'asc' ? 'desc' : 'asc';
    } else {
      this.sortBy = sortBy;
      this.sortOrder = 'desc';
    }
    this.applyFilters();
  }

  downloadHistoryItem(item) {
    if (item.downloadUrl && item.status === 'success') {
      const link = document.createElement('a');
      link.href = item.downloadUrl;
      link.download = item.convertedName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  }

  exportHistory() {
    const exportData = this.history.map(item => ({
      timestamp: item.timestamp,
      originalName: item.originalName,
      sourceFormat: item.sourceFormat,
      targetFormat: item.targetFormat,
      fileSize: item.fileSize,
      status: item.status,
      error: item.error
    }));

    const dataStr = JSON.stringify(exportData, null, 2);
    const dataBlob = new Blob([dataStr], { type: 'application/json' });
    const url = URL.createObjectURL(dataBlob);
    
    const link = document.createElement('a');
    link.href = url;
    link.download = `conversion-history-${new Date().toISOString().split('T')[0]}.json`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    URL.revokeObjectURL(url);
  }

  formatTimestamp(timestamp) {
    const date = new Date(timestamp);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  }

  getStatusText(status) {
    switch (status) {
      case 'success':
        return '成功';
      case 'error':
        return '失败';
      case 'pending':
        return '等待中';
      case 'converting':
        return '转换中';
      default:
        return '未知';
    }
  }

  getStatusClass(status) {
    switch (status) {
      case 'success':
        return 'status-success';
      case 'error':
        return 'status-error';
      case 'pending':
        return 'status-pending';
      case 'converting':
        return 'status-converting';
      default:
        return 'status-unknown';
    }
  }

  getFormatIcon(format) {
    const formatMap = {
      'docx': '📄',
      'md': '📝',
      'pdf': '📋',
      'txt': '📃'
    };
    return formatMap[format] || '📄';
  }

  getUniqueFormats() {
    const formats = new Set();
    this.history.forEach(item => {
      formats.add(item.sourceFormat);
      formats.add(item.targetFormat);
    });
    return Array.from(formats).sort();
  }

  getStatistics() {
    const total = this.history.length;
    const successful = this.history.filter(item => item.status === 'success').length;
    const failed = this.history.filter(item => item.status === 'error').length;
    const successRate = total > 0 ? Math.round((successful / total) * 100) : 0;

    return {
      total,
      successful,
      failed,
      successRate
    };
  }
} 